package com.redeemer150.aisuperagent.tools;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.util.HashMap;
import java.util.Map;


public class GoogleWebSearchTool {

    private static final String SEARCH_API_URL = "https://www.searchapi.io/api/v1/search";
    private final String apiKey;

    public GoogleWebSearchTool(String apiKey) {
        // 从配置读取API密钥（推荐在application.yml中配置）
        this.apiKey = apiKey;
    }

    @Tool(name = "googleSearch", description = "使用Google搜索引擎进行网页搜索")
    public String searchWeb(
            @ToolParam(description = "搜索关键词或问题") String query
    ) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("q", query);
            params.put("api_key", apiKey);
            params.put("engine", "google");


            String response = HttpUtil.get(SEARCH_API_URL, params);
            return processApiResponse(response);

        } catch (Exception e) {
            return "搜索失败: " + e.getMessage();
        }
    }

    private String processApiResponse(String jsonResponse) {
        JSONObject responseObj = JSONUtil.parseObj(jsonResponse);

        // 1. 优先返回知识图谱
        if (responseObj.containsKey("knowledge_graph")) {
            JSONObject kg = responseObj.getJSONObject("knowledge_graph");
            return formatKnowledgeGraph(kg);
        }

        // 2. 返回普通搜索结果
        if (responseObj.containsKey("organic_results")) {
            JSONArray results = responseObj.getJSONArray("organic_results");
            return formatOrganicResults(results);
        }

        return "未找到相关信息";
    }

    private String formatKnowledgeGraph(JSONObject kg) {
        StringBuilder sb = new StringBuilder("【知识图谱结果】\n");
        sb.append("标题: ").append(kg.getStr("title", "无")).append("\n");
        sb.append("类型: ").append(kg.getStr("type", "无")).append("\n");
        sb.append("评分: ").append(kg.getStr("rating", "无")).append("\n");
        sb.append("地址: ").append(kg.getStr("address", "无")).append("\n");
        sb.append("网站: ").append(kg.getStr("website", "无")).append("\n");
        return sb.toString();
    }

    private String formatOrganicResults(JSONArray results) {
        StringBuilder sb = new StringBuilder("【搜索结果】\n");
        int limit = Math.min(results.size(), 5);

        for (int i = 0; i < limit; i++) {
            JSONObject item = results.getJSONObject(i);
            sb.append(i + 1).append(". ")
                    .append(item.getStr("title", "无标题")).append("\n")
                    .append("  链接: ").append(item.getStr("link", "无")).append("\n")
                    .append("  摘要: ").append(item.getStr("snippet", "无")).append("\n\n");
        }
        return sb.toString();
    }
}